// 促销活动配置功能实现

DOM.on(window, 'load', () => {
  let currentPage = 1;
  const pageSize = 10;
  
  // 渲染促销活动表格
  function renderPromotions() {
    const promotionsTable = DOM.$('#promotions-table tbody');
    promotionsTable.innerHTML = '';
    
    const promotions = dataManager.data.promotions;
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedPromotions = promotions.slice(startIndex, endIndex);
    const totalPages = Math.ceil(promotions.length / pageSize);
    
    if (paginatedPromotions.length === 0) {
      const emptyRow = DOM.create('tr');
      emptyRow.innerHTML = `
        <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
          暂无促销活动
        </td>
      `;
      promotionsTable.appendChild(emptyRow);
      return;
    }
    
    paginatedPromotions.forEach(promotion => {
      const row = DOM.create('tr');
      
      // 格式化日期
      const startDate = new Date(promotion.startDate).toLocaleDateString('zh-CN');
      const endDate = new Date(promotion.endDate).toLocaleDateString('zh-CN');
      
      // 状态徽章样式
      let badgeClass = '';
      switch (promotion.status) {
        case '未开始': badgeClass = 'badge-primary'; break;
        case '进行中': badgeClass = 'badge-success'; break;
        case '已结束': badgeClass = 'badge-secondary'; break;
      }
      
      row.innerHTML = `
        <td>${promotion.id}</td>
        <td>${promotion.name}</td>
        <td>${promotion.type}</td>
        <td>${startDate}</td>
        <td>${endDate}</td>
        <td><span class="badge ${badgeClass}">${promotion.status}</span></td>
        <td>
          <button class="btn btn-secondary" style="padding: 4px 12px; font-size: 12px; margin-right: 5px;" data-promo-id="${promotion.id}" data-action="edit">
            编辑
          </button>
          <button class="btn btn-secondary" style="padding: 4px 12px; font-size: 12px; margin-right: 5px;" data-promo-id="${promotion.id}" data-action="view">
            查看
          </button>
          <button class="btn btn-danger" style="padding: 4px 12px; font-size: 12px;" data-promo-id="${promotion.id}" data-action="delete">
            删除
          </button>
        </td>
      `;
      
      promotionsTable.appendChild(row);
    });
    
    // 绑定操作按钮事件
    bindPromotionActions();
    
    // 渲染分页
    renderPagination(totalPages, currentPage);
  }
  
  // 绑定促销活动操作按钮事件
  function bindPromotionActions() {
    DOM.$$('#promotions-table [data-action]').forEach(btn => {
      DOM.on(btn, 'click', () => {
        const promoId = btn.getAttribute('data-promo-id');
        const action = btn.getAttribute('data-action');
        
        switch (action) {
          case 'edit':
            editPromotion(promoId);
            break;
          case 'view':
            viewPromotion(promoId);
            break;
          case 'delete':
            deletePromotion(promoId);
            break;
        }
      });
    });
  }
  
  // 编辑促销活动
  function editPromotion(promoId) {
    const promotion = dataManager.data.promotions.find(p => p.id === promoId);
    if (promotion) {
      alert(`编辑促销活动: ${promotion.name}`);
      // 这里可以打开编辑模态框并填充数据
    }
  }
  
  // 查看促销活动详情
  function viewPromotion(promoId) {
    const promotion = dataManager.data.promotions.find(p => p.id === promoId);
    if (promotion) {
      let details = `促销活动详情\n\n`;
      details += `活动ID: ${promotion.id}\n`;
      details += `活动名称: ${promotion.name}\n`;
      details += `活动类型: ${promotion.type}\n`;
      details += `开始日期: ${new Date(promotion.startDate).toLocaleDateString('zh-CN')}\n`;
      details += `结束日期: ${new Date(promotion.endDate).toLocaleDateString('zh-CN')}\n`;
      details += `活动状态: ${promotion.status}\n`;
      details += `活动描述: ${promotion.description}\n`;
      
      alert(details);
    }
  }
  
  // 删除促销活动
  function deletePromotion(promoId) {
    if (confirm('确定要删除该促销活动吗？')) {
      const index = dataManager.data.promotions.findIndex(p => p.id === promoId);
      if (index !== -1) {
        dataManager.data.promotions.splice(index, 1);
        dataManager.saveToStorage();
        renderPromotions();
      }
    }
  }
  
  // 渲染分页控件
  function renderPagination(totalPages, current) {
    // 移除旧的分页控件
    const oldPagination = DOM.$('#promotions-table + .pagination');
    if (oldPagination) {
      oldPagination.remove();
    }
    
    // 创建新的分页控件
    const tableContainer = DOM.$('#promotions-table').parentElement;
    const pagination = DOM.create('div', 'pagination');
    
    // 上一页
    const prevBtn = DOM.create('button');
    prevBtn.innerHTML = '‹';
    prevBtn.disabled = current === 1;
    DOM.on(prevBtn, 'click', () => {
      if (current > 1) {
        currentPage--;
        renderPromotions();
      }
    });
    pagination.appendChild(prevBtn);
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
      const pageBtn = DOM.create('button');
      pageBtn.textContent = i;
      if (i === current) {
        pageBtn.classList.add('active');
      }
      DOM.on(pageBtn, 'click', () => {
        currentPage = i;
        renderPromotions();
      });
      pagination.appendChild(pageBtn);
    }
    
    // 下一页
    const nextBtn = DOM.create('button');
    nextBtn.innerHTML = '›';
    nextBtn.disabled = current === totalPages;
    DOM.on(nextBtn, 'click', () => {
      if (current < totalPages) {
        currentPage++;
        renderPromotions();
      }
    });
    pagination.appendChild(nextBtn);
    
    tableContainer.appendChild(pagination);
  }
  
  // 创建新促销活动
  function createPromotion() {
    alert('创建新促销活动功能');
    // 这里可以打开创建促销活动的模态框
  }
  
  // 初始化促销活动管理页面
  function initPromotions() {
    // 绑定创建活动按钮事件
    const createBtn = DOM.$('#promotions-view .btn-primary');
    if (createBtn) {
      DOM.on(createBtn, 'click', createPromotion);
    }
    
    // 监听视图切换事件
    DOM.on(document, 'viewChanged', (e) => {
      if (e.detail.viewId === 'promotions') {
        currentPage = 1;
        renderPromotions();
      }
    });
  }
  
  // 初始化
  initPromotions();
});